package com.changgou.system.controller;
import com.changgou.common.pojo.Result;
import com.changgou.common.pojo.StatusCode;

import com.changgou.system.pojo.Admin;
import com.changgou.system.service.AdminService;
import com.changgou.system.util.JwtUtil;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {


    @Autowired
    private AdminService adminService;

    @PostMapping
    public Result add(@RequestBody Admin admin){
        adminService.add(admin);
        return new Result(true, StatusCode.OK,"添加成功");
    }

    @PostMapping("/login")
    private Result login(@RequestBody Admin admin){
        boolean flag = adminService.login(admin);
        if (flag){
            Map<String, String> hashMap = new HashMap<>();
            hashMap.put("username",admin.getLoginName());

            //基于工具类生成jwt令牌
            String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), admin.getLoginName(), null);

            //获取当前时间毫秒数
            long currentTimeMillis = System.currentTimeMillis();

            //设置jwt过时时间
            long expTime = currentTimeMillis + 60*60*1000L;
/*            //创建jwt令牌
            JwtBuilder jwtBuilder = Jwts.builder()
                    .setId(UUID.randomUUID().toString())    //设置唯一编号
                    .setSubject(admin.getLoginName())       //设置主题
                    .setIssuer("admin")         //设置签发者
                    .setIssuedAt(new Date(currentTimeMillis))   //设置签发日期为当前时间
                    .setExpiration(new Date(expTime))       //设置过期时间
                    .signWith(SignatureAlgorithm.HS256, "")  //设置签名 使用HS256算法， 并设置SecretKey(字符串)
                    .claim("roles", "admin");       //存储更多的信息
            //构建返回一个字符串
            String compact = jwtBuilder.compact();*/

            hashMap.put("token",jwt);

            return new Result(true,StatusCode.OK,"登录成功",hashMap);
        }else {
            return new Result(false,StatusCode.ERROR,"登录失败");
        }
    }

}
